import 'dart:io';

import 'package:app/common/save_update.dart';
import 'package:app/model/product_sale_out.dart';
import 'package:app/shop_cart.dart';
import 'package:flutter/material.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import 'common/global.dart';
import 'package:dio/dio.dart';
import 'dart:convert';
import 'package:flutter/services.dart' show ByteData, rootBundle;

import 'common/product_card.dart';
import 'common/shop_cart_card.dart';
import 'model/product_view_model.dart';

void main() {
  Global.init().then((e) => runApp(MultiProvider(
        providers: [
          ChangeNotifierProvider.value(value: GlobalData()),
          ChangeNotifierProvider.value(value: MainList())
        ],
        child: MyAppPage(),
      )));
}

class MyAppPage extends StatefulWidget {
  MyAppPage({Key key}) : super(key: key);

  @override
  _MyAppPageState createState() => new _MyAppPageState();
}

class _MyAppPageState extends State<MyAppPage> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    var _currentTheme = Provider.of<GlobalData>(context).currentTheme;
    return new MaterialApp(
        title: 'Generated App',
        theme: new ThemeData(
          primaryColor: _currentTheme,
          fontFamily: 'Roboto',
        ),
        home: MyHomePage());
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  TabController _controller;

  @override
  void initState() {
    super.initState();
    MainList.initTabMap();
    //加载数据
    _controller = TabController(vsync: this, length: MainList.myTabs.length);
    GlobalData.initSaleOutList();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      drawer: buildDrawer(),
      appBar: buildAppBar(),
      body: buildTabBarView()
    );
  }

  Padding buildPadding(BuildContext context) {
    var _currentTheme = Provider.of<GlobalData>(context).currentTheme;
    return Padding(
        padding: const EdgeInsets.only(right: 60.0),
        child: FloatingActionButton(
          tooltip: '新增', // used by assistive technologies
          child: new Icon(Icons.add),
          backgroundColor: _currentTheme,
          onPressed: () async {
            String result =
                await Navigator.of(context).push(new MaterialPageRoute(
                    builder: (context) => new SaveUpdatePage(
                          action: "新增",
                        )));
            if (result != null) {
              //重新加载列表数据
              Provider.of<MainList>(context).reloadByType(result);
            }
          },
        ));
  }

  TabBarView buildTabBarView() {
    return TabBarView(
        controller: _controller,
        children: Provider.of<MainList>(context)
            .getTabMaps
            .values
            .map<Widget>((MyTab _myTab) {
          return SafeArea(
            top: false,
            bottom: false,
            child: Builder(
              builder: (BuildContext context) {
                if (_myTab.productList != null) {
                  return ListView.separated(
                    itemCount: _myTab.productList.length,
                    itemBuilder: (context, index) {
                      return new ProductCard(
                          data: new ProductViewModel(
                              id: _myTab.productList[index]["id"],
                              productName: _myTab.productList[index]
                                  ["productName"],
                              priceSale: _myTab.productList[index]["priceSale"],
                              priceBig:
                                  _myTab.productList[index]["priceBig"] == null
                                      ? "0"
                                      : _myTab.productList[index]["priceBig"],
                              img: _myTab.productList[index]["img"],
                              productType: _myTab.productList[index]
                                  ["productType"]));
                    },
                    separatorBuilder: (context, index) {
                      return Divider(
                        height: 1,
                        indent: 75,
                        color: Color(0xFFDDDDDD),
                      );
                    },
                  );
                } else {
                  //重新加载数据
                  Provider.of<MainList>(context).reloadByType(_myTab.getType());
                  return Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      SizedBox(
                        height: 50,
                        width: 50,
                        child: CircularProgressIndicator(
                          backgroundColor: Colors.pink,
                        ),
                      )
                    ],
                  );
                }
              },
            ),
          );
        }).toList());
  }

  AppBar buildAppBar() {
    return AppBar(
      title: Text('产品'),
      //drawer: new Drawer(),
      actions: <Widget>[
        //behavior: HitTestBehavior.opaque,
        Padding(
            padding: const EdgeInsets.only(right: 15.0),
            child: GestureDetector(
              child: Icon(Icons.add),
              onTap: () async {
                String result =
                await Navigator.of(context).push(new MaterialPageRoute(
                    builder: (context) => new SaveUpdatePage(
                      action: "新增",
                    )));
                if (result != null) {
                  //重新加载列表数据
                  Provider.of<MainList>(context).reloadByType(result);
                }
              },
              onLongPress: () =>
                  Provider.of<GlobalData>(context).clearShopCartCount(),
              onVerticalDragEnd: (endDetails) {
                Provider.of<GlobalData>(context).clearShopCartCount();
              },
            )),
        GestureDetector(
          //behavior: HitTestBehavior.opaque,
          child: Icon(Icons.shopping_cart),
          onTap: () => Navigator.of(context).push(
              new MaterialPageRoute(builder: (context) => new ShopCartPage())),
          onLongPress: () =>
              Provider.of<GlobalData>(context).clearShopCartCount(),
          onVerticalDragEnd: (endDetails) {
            Provider.of<GlobalData>(context).clearShopCartCount();
          },
        ),
        Consumer<GlobalData>(
            builder: (context, globalData, _) =>
                Text(globalData.shopCartCount.toString(),
                    style: TextStyle(
                        //fontSize:11,
                        height: 2))),
        //Center(child: Text("11")),
        PopupMenuButton<String>(
          offset: Offset(0, 200),
          //onSelected: ,
          //onSelected: handleDemoAction,
          itemBuilder: (BuildContext context) => Global.themes.keys
              .map((x) => new PopupMenuItem(
                    child: Text(x),
                    value: x,
                  ))
              .toList(),
          onSelected: _changeTheme,
        ),
      ],
      iconTheme: IconThemeData(color: Colors.white),
      textTheme: TextTheme(
        title: TextStyle(
          color: Colors.white,
          fontSize: 20.0,
        ),
      ),
      bottom: new TabBar(
        isScrollable: true,
        tabs: Provider.of<MainList>(context).getMyTabs,
        indicatorColor: Colors.white,
        controller: _controller,
      ),
    );
  }

  void _openFile() async {
    Directory dir = await getExternalStorageDirectory();
    File file = File("${dir.path}/hfjd.docx");
    //不存在时先写入
    if (!file.existsSync()) {
      ByteData byteData = await rootBundle.load("assets/hfjd.docx");
      await file.writeAsBytes(byteData.buffer.asInt8List(0));
    }
    String url = "${dir.path}/hfjd.docx";

    OpenFile.open(url);
  }

  void _openOffice() async {
    var url = "kingsoftofficeapp://";
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

  Drawer buildDrawer() {
    return new Drawer(
        child: Column(
      children: <Widget>[
        Consumer<GlobalData>(
          builder: (context, globalData, _) => Container(
            height: 128,
            color: globalData.currentTheme,
            child: Container(
              margin: EdgeInsets.only(top: 30),
              child: Row(
                children: <Widget>[
                  Padding(padding: EdgeInsets.all(10)),
                  ClipRRect(
                      borderRadius: BorderRadius.circular(40),
                      child: Image.asset(
                        "assets/201905141517518.png",
                        width: 60,
                        height: 60,
                      )),
                  Padding(padding: EdgeInsets.all(10)),
                  Text("大喵喵",
                      style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.w900,
                          fontSize: 24)),
                  Padding(padding: EdgeInsets.all(10)),
                  RaisedButton(
                    color: Colors.red,
                    child: Text(
                      "暴力刷新",
                    ),
                    onPressed: () => Provider.of<MainList>(context).reloadAll(),
                  )
                ],
              ),
            ),
          ),
        ),
        ListTile(
          leading: Icon(Icons.collections_bookmark),
          title: new Text('打开Office'),
          onTap: _openOffice,
        ),
        ListTile(
          leading: Icon(Icons.chrome_reader_mode),
          title: new Text('打开护肤宝典'),
          onTap: _openFile,
        ),
        ListTile(
          leading: Icon(Icons.chrome_reader_mode),
          title: new Text('统计'),
        ),
        Text("售出统计",
            style: TextStyle(
                color: Colors.red, fontSize: 18, fontWeight: FontWeight.w300)),
        SizedBox(
          height: 400.0,
          child: Container(
            child: Consumer<GlobalData>(
              builder: (context, globalData, _) => ListView.separated(
                itemCount: globalData.listSaleOut.length,
                itemBuilder: (context, index) {
                  return Row(
                    children: <Widget>[
                      Expanded(
                          child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: <Widget>[
                              Padding(
                                padding: const EdgeInsets.only(left: 16.0),
                                child: Text(
                                  globalData.listSaleOut[index].dateTime
                                      .toString()
                                      .substring(0, 16),
                                  style: TextStyle(
                                      color: Colors.black54,
                                      fontSize: 18,
                                      fontWeight: FontWeight.w300),
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsets.only(right: 18.0),
                                child: Text(
                                  globalData.listSaleOut[index].priceSale
                                          .toString() +
                                      "-" +
                                      globalData.listSaleOut[index].priceBig
                                          .toString() +
                                      "=" +
                                      globalData.listSaleOut[index].money
                                          .toString(),
                                  style: TextStyle(
                                      color: Colors.red,
                                      fontSize: 18,
                                      fontWeight: FontWeight.w300),
                                ),
                              )
                            ],
                          ),
                          Padding(
                            padding:
                                const EdgeInsets.only(left: 38.0, right: 38),
                            child: Text(
                              globalData.listSaleOut[index].content,
                              style: TextStyle(
                                  fontSize: 10, color: Colors.black54),
                            ),
                          ),
                        ],
                      ))
                    ],
                  );
                },
                separatorBuilder: (context, index) {
                  return Divider(
                    height: 1,
                    indent: 75,
                    color: Color(0xFFDDDDDD),
                  );
                },
              ),
            ),
          ),
        ),
      ],
    ));
  }

  void _changeTheme(String value) async {
    //MaterialColor  materialColor= await Global.changeTheme(value);
    Provider.of<GlobalData>(context).changeTheme(value);
  }
}
